package com.yanlin.servicemap.client;

import com.yanlin.internalcommon.dto.ResponseResult;
import com.yanlin.internalcommon.response.DicDirectionResponse;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import static com.yanlin.internalcommon.constant.AmapConstant.*;

/**
 * <p>标题：DirectionClient</p>
 * <p>功能：</p>
 * <p>
 * 其他说明：
 * </p>
 * <p>审核：</p>
 * <p>重构：</p>
 * <p>创建日期：2025-06-09 17:40</p>
 *
 * @author yanlin
 */
@Service
@Slf4j
public class MapDirectionClient {

    @Value("${amap.key}")
    private String amapKey;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 调用amap服务，获取距离和时间
     * @param depLongitude
     * @param depLatitude
     * @param destLongitude
     * @param destLatitude
     * @return
     */
    public ResponseResult direction(String depLongitude, String depLatitude, String destLongitude, String destLatitude) {

        log.info("service-map client: 出发地经度={}, 出发地纬度={}, 目的地经度={}, 目的地纬度={}",
                depLongitude, depLatitude, destLongitude, destLatitude);
        StringBuilder url = new StringBuilder();
        url.append(AMP_URI).append("/direction/driving");
        url.append("?origin=").append(depLongitude).append(",").append(depLatitude);
        url.append("&destination=").append(destLongitude).append(",").append(destLatitude);
        url.append("&extensions=all&output=json");
        url.append("&key=").append(amapKey);
        log.info("amap api url : {}", url);

        // 调用amap服务api
        ResponseEntity<String> res = restTemplate.getForEntity(url.toString(), String.class);
        DicDirectionResponse dicDirectionResponse = parseDirectionEntity(res.getBody());
        return ResponseResult.success(dicDirectionResponse);
    }

    /**
     * 解析amap 响应参数
     * @param directionEntity
     * @return
     */
    private DicDirectionResponse parseDirectionEntity(String directionEntity) {
        DicDirectionResponse dicDirectionResponse = new DicDirectionResponse();
        JSONObject jsonDirection = null;
        try {
            jsonDirection = JSONObject.fromObject(directionEntity);
            if (jsonDirection.has(AMAP_STATUS)) {
                int status = jsonDirection.getInt(AMAP_STATUS);
                if (status == 1) {
                    if (jsonDirection.has(AMAP_ROUTE)) {
                        JSONObject jsonRoute = jsonDirection.getJSONObject(AMAP_ROUTE);
                        if (jsonRoute.has(AMAP_PATHS)) {
                            JSONArray jsonPaths = jsonRoute.getJSONArray(AMAP_PATHS);
                            // 获取第一条路线规划
                            JSONObject jsonPath = jsonPaths.getJSONObject(0);
                            if (jsonPath.has(AMAP_DISTANCE)) {
                                dicDirectionResponse.setDistance(jsonPath.getInt(AMAP_DISTANCE));
                            }
                            if (jsonPath.has(AMAP_DURATION)) {
                                dicDirectionResponse.setDuration(jsonPath.getInt(AMAP_DURATION));
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.warn("amap json parse error");
        }
        return dicDirectionResponse;
    }
}